package com.shengdong.water.code.utils

import android.graphics.Color
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextPaint
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.text.style.UnderlineSpan
import android.view.View

object SpannableUtil {
    /**
     * 创建标签值对的彩色文本，支持值的点击和下划线
     * @param label 标签文本
     * @param value 值文本
     * @param labelColor 标签颜色
     * @param valueColor 值颜色
     * @param valueUnderline 值是否添加下划线
     * @param valueClickable 值是否可点击
     * @param onValueClick 值的点击事件回调
     */
    fun createLabelValueSpan(
        label: String,
        value: String,
        labelColor: Int = Color.BLACK,
        valueColor: Int,
        valueUnderline: Boolean = false,
        valueClickable: Boolean = false,
        onValueClick: (() -> Unit)? = null
    ): SpannableStringBuilder {
        val fullText = "$label$value"
        val spannableString = SpannableStringBuilder(fullText)

        // 设置标签颜色
        spannableString.setSpan(
            ForegroundColorSpan(labelColor),
            0,
            label.length,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )

        // 设置值的样式（颜色、下划线、点击）
        val valueStartIndex = label.length
        val valueEndIndex = fullText.length

        // 设置值的颜色
        spannableString.setSpan(
            ForegroundColorSpan(valueColor),
            valueStartIndex,
            valueEndIndex,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )

        // 如果需要下划线
        if (valueUnderline) {
            spannableString.setSpan(
                UnderlineSpan(),
                valueStartIndex,
                valueEndIndex,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
        }

        // 如果需要点击事件
        if (valueClickable && onValueClick != null) {
            val clickableSpan = object : ClickableSpan() {
                override fun updateDrawState(ds: TextPaint) {
                    ds.color = valueColor
                    ds.isUnderlineText = valueUnderline
                }

                override fun onClick(view: View) {
                    onValueClick.invoke()
                }
            }

            spannableString.setSpan(
                clickableSpan,
                valueStartIndex,
                valueEndIndex,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
        }

        return spannableString
    }

    /**
     * 合并多个SpannableStringBuilder
     */
    fun combineSpannables(vararg spannables: SpannableStringBuilder, separator: String = "\n"): SpannableStringBuilder {
        return SpannableStringBuilder().apply {
            spannables.forEachIndexed { index, spannable ->
                append(spannable)
                if (index < spannables.size - 1) {
                    append(separator)
                }
            }
        }
    }
}